

from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

#from myapp.models import User
import json

from rest_framework.response import Response
from rest_framework.views import APIView

# from mydjango.test_md5 import make_password,check_passwor
from . import myser
from .models import *
from django.contrib.auth.hashers import check_password
from mydjango.settings import SECRET_KEY
#导入加密库
import hashlib
#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#引入密钥
app_private_key_string = os.path.join(BASE_DIR,"keys/app_private_2048.txt")
alipay_public_key_string = os.path.join(BASE_DIR,"keys/alipay_public_2048.txt")

from mydjango.pay import AliPay


#建立支付实例
def get_ali_object():

	app_id = "2016092600603658"  #  APPID （沙箱应用）
	# 支付完成后，跳转的地址。
	return_url = "http://localhost:8000/testpay/"
	alipay = AliPay(
	    appid=app_id,
	    app_notify_url=return_url,
	    return_url=return_url,
	    app_private_key_path=app_private_key_string,
	    alipay_public_key_path=alipay_public_key_string,  # 支付宝的公钥，验证支付宝回传消息使用，不是你自己的公钥
	    debug=True,  # 默认False,
	)
	return alipay

#支付跳转视图
def pay_url(request):

	alipay = get_ali_object()

	# 生成支付的url
	query_params = alipay.direct_pay(
	    subject="test",  # 商品简单描述
	    out_trade_no="myorder" + str(time.time()),
	    total_amount = 10.00,  # 交易金额(单位: 元 保留俩位小数)
	)

	pay_url = "https://openapi.alipaydev.com/gateway.do?{0}".format(query_params)  # 支付宝网关地址（沙箱应用）

	return redirect(pay_url)


from django.db import transaction
import hashlib
#方法视图
def myindex(request):

	return HttpResponse("你好啊，这里是在线教育平台")
import re

def make_password(mypass):
		md5 = hashlib.md5()
		#定义加密对象
		sign_str = mypass
		#转码
		sign_utf8 = str(sign_str).encode(encoding='utf-8')
		#加密
		md5.update(sign_utf8)
		#生成密文
		md5_server = md5.hexdigest()

		return md5_server


# #用户注册
# class Registers(APIView):
# 	def post(self,request):
# 		#接收参数
# 		username = request.data.get('username')
# 		password = request.data.get('password')
# 		pthone = request.data.get('pthone')
# 		emial = request.data.get('emial')
# 		# 拍重
# 		print(username,password)
# 		try:
# 			ret = re.match(r"^1[345678]\d{9}$", pthone)
# 			if ret:
# 				ex_email = re.compile(r'^[1-9][0-9]{4,10}@qq.com',emial)
# 				if ex_email:
# 					# user = User.objects.filter(username = username).first()
# 					# if user:
# 					# 	return Response({'code':400,'msg':'用户存在'})
# 					user = User(username=username,password=make_password(password),pthone=pthone,emial=emial)
# 					user.save()
# 					return Response({'code':200,'msg':'成功'})
# 				return Response({'code':401,'msg':'邮箱不合格'})
# 			return Response({'code': 400, 'msg': '手机号不合格'})
# 		except Exception as e:
# 			print(str(e))
# 			return Response({'code':405,'msg':'用户存在'})


# class Mycode(APIView):
# 	def get_random_color(self):
# 		R = random.randrange(255)
# 		G = random.randrange(255)
# 		B = random.randrange(255)
# 		return (R,G,B)
# 	def get(self,request):
# 		#定义画布
# 		img_size = (120,50)
#
# 		#定义图像对象
# 		image = Image.new('RGB',img_size,'white')
# 		#定义画笔
# 		draw = ImageDraw.Draw(image,'RGB')
# 		#定义字符串
# 		source = 'qwertiop234gh'
# 		#定义容器
# 		code_str = ''
# 		for i in range(4):
# 			#获取字符串颜色
# 			text_color = self.get_random_color()
# 			#获取随机字符
# 			tem_num = random.randrange(len(source))
# 			random_str = source[tem_num]
# 			code_str += random_str
# 			draw.text((10+30*i,20),random_str,text_color)
# 		buf = io.BytesIO()
# 		image.save(buf,'png')
# 		#保存验证码
# 		request.session['code'] = code_str
#
# 		r = redis.Redis()
#
# 		r.set('code',code_str)
#
# 		return HttpResponse(buf.getvalue(),'image/pag')








class Registers(APIView):
	def post(self, request):
		# 接收参数
		username = request.data.get('username','' )
		password = request.data.get('password','' )
		emial = request.data.get('emial','' )
		pthone = request.data.get('phone', '')
		password1 = request.data.get('password1', '')
		try:
			if re.search('^1[0-9]\d{9}$', pthone):
				if password == password1:
					user = User(username=username, password=make_password(password), pthone=pthone,
							emial=emial)
					user.save()
					return Response({"msg": '注册成功', 'code': 200})
				else:
					return Response({"msg": '两次密码不一致', 'code': 400})
			else:
				return Response({"msg": "手机号不合格", 'code': 400})
		except Exception as e:
			print(e)
			return Response({"msg": '用户名已存在', 'code': 405})
#用户登录
class Login(APIView):
	def post(self,resquest):
		username = resquest.data.get('username',None)
		password = resquest.data.get('password',None)
		active = resquest.data.get('active')

		if active == 0:
			user = User.objects.filter(username=username).first()
			if user:
				if check_password(password, user.password):
					encode_jwt = jwt.encode({'uid': user.id, 'username': user.username}, '123', algorithm='HS256')
					token = str(encode_jwt, 'utf-8')
					return Response({'msg': '登录成功', 'code': 200,'token':token})
				else:
					return Response({'msg': '密码或用户名错误', 'code': 400})
			else:
				return Response({'msg': '登录失败', 'code': 405})
		elif active == 1:
			user = User.objects.filter(pthone=username).first()
			if user:
				if check_password(password, user.password):
					encode_jwt = jwt.encode({'uid': user.id, 'username': user.username}, '123', algorithm='HS256')
					token = str(encode_jwt, 'utf-8')
					print(token)
					return Response({'msg': '登录成功', 'code': 200,'token':token})
				else:
					return Response({'msg': '密码或手机号错误', 'code': 400})
			return Response({'msg': '登录失败', 'code': 405})
		else:
			user = User.objects.filter(emial=username).first()
			if user:
				if check_password(password, user.password):
					encode_jwt = jwt.encode({'uid': user.id, 'username': user.username}, '123', algorithm='HS256')
					token = str(encode_jwt, 'utf-8')
					return Response({'msg': '登录成功', 'code': 200,'token':token})
				else:
					return Response({'msg': '密码或邮箱错误', 'code': 400})
			else:
				return Response({'msg': '登录失败', 'code': 405})



res = requests.get("https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=X1kkwVwvnoSbONGEyL88AZrP&client_secret=HeH5pTRPBf2FbRGsqSAh0YvFKT2C6dvt")

res = json.loads(str(res.text))
token = res['access_token']
print(token)

class Make_tu(APIView):
	def get(self,requset):
		import base64
		import json
		import urllib.parse
		temp_url = 'https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic?access_token=' + '24.0213754a8cd7a03937957c7bbb8be9fb.2592000.1613033612.282335-23530724'
		temp_headers = {'Content-Type': 'application/x-www-form-urlencoded'}
		temp_file = open('123.png', 'rb')
		temp_image = temp_file.read()
		temp_file.close()
		temp_data = {'image': base64.b64encode(temp_image)}
		temp_data = urllib.parse.urlencode(temp_data)
		temp_res = requests.post(url=temp_url, data=temp_data, headers=temp_headers)

		res = json.loads(str(temp_res.text))
		code = res['words_result'][0]['words']
		print(code)

# nodes = driver.find_element_by_id('loginImgVcode')
# nodes.screenshot('123.png')
from myapp.myser import Allserializers
from .models import User
class Allview(APIView):
		def get(self, request):
			id = request.data.get('id')
			obj_user = User.objects.filter(id=id)
			obj = Allserializers(obj_user, many=True)
			return Response(obj.data)

		def put(self, request):
			password = request.data.get('password')
			user_obj = User.objects.get(id=request.id)
			user_obj.password = make_password(password)
			user_obj.save()
			return Response({'msg': '修改成功,请登录', 'code': 200})

